﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdvanceLib.ScriptCore;
using AdvanceLib.ScriptCore.DebugCore;

namespace AdvanceLib.Extension.Root.DebugPasses
{
    public class ParameterCountPass : CommandPass, IFinalPass
    {
        #region Constructors
        public ParameterCountPass(RootProvider provider)
        {
            this._host = provider.Host;
        }
        #endregion

        #region Fields
        private ScriptHost _host;
        private string _commandName;
        private List<ISystemCommand> _commands;
        private int _paramCount = 0;
        #endregion

        #region CommandPass Members
        public override void Pass(DebugResult result, string input)
        {
            if (this.CurrentLinePartIndex == 0 &&
                this.CurrentLine.StartsWith(this._host.SystemCommandInitialization))
            {
                this._commandName = input.Substring(this._host.SystemCommandInitialization.Length);
                this._commands = this._host.ExtensionManager.GetSystemCommandsByName(this._commandName);

                this._paramCount = 0;
            }
            else if (this._commands != null)
            {
                this._paramCount++;
            }
        }
        #endregion

        #region IFinalPass Member
        public void FinalPass(DebugResult result)
        {
            bool commandHit = false;
            if (this._commands != null)
            {
                foreach (ISystemCommand command in this._commands)
                    if (command.ExpectedParameters == this._paramCount) commandHit = true;

                if (this._commands.Count > 0 && !commandHit)
                {
                    StringBuilder messageBuilder = new StringBuilder();
                    messageBuilder.Append("Systemcommand '");
                    messageBuilder.Append(this._commandName);
                    messageBuilder.Append("' expects ");
                    messageBuilder.Append(this._commands[Constants.FIRST_INDEX].ExpectedParameters.ToString());

                    for (int i = 1; i < this._commands.Count; i++)
                    {
                        messageBuilder.Append(" or ");
                        messageBuilder.Append(this._commands[i].ExpectedParameters.ToString());
                    }

                    messageBuilder.Append(" parameter(s).");

                    result.Errors.Add(new DebugError()
                    {
                        Line = this.CurrentLineIndex,
                        Message = messageBuilder.ToString()
                    });
                }
                this._commands.Clear();
            }
        }
        #endregion
    }
}
